package com.glory.gloryquickui.base

import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.glory.gloryquickui.R
import com.glory.gloryquickui.utils.FreeApi_ToastUtils
import kotlinx.android.synthetic.main.view_title.*
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

abstract class BaseActivity<VM : BaseViewModel> : AppCompatActivity(),
    IBaseView {

    protected lateinit var viewModel: VM

//    protected lateinit var mBinding: DB w

    private var dialog: MaterialDialog? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initViewDataBinding()
        //强制竖屏
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        initViewTitle()
        //注册 UI事件
        lifecycle.addObserver(viewModel)
        registerDefUIChange()
        initView(savedInstanceState)
        initData()
    }

    abstract fun layoutId(): Int
//    abstract fun initVariableId(): Int
    abstract fun initView(savedInstanceState: Bundle?)
    abstract fun initData()

    /**
     * DataBinding or ViewBinding
     */
    private fun initViewDataBinding() {
        var type = javaClass.superclass.genericSuperclass
        if (javaClass.superclass.name == "com.glory.gloryquickui.base.BaseActivity") {
            type = javaClass.genericSuperclass
        }
        if (type is ParameterizedType) {
            setContentView(layoutId())
//            val cls = type.actualTypeArguments[1] as Class<*>
//            when {
//                ViewDataBinding::class.java.isAssignableFrom(cls) && cls != ViewDataBinding::class.java -> {
//                    if (layoutId() == 0) throw IllegalArgumentException("Using DataBinding requires overriding method layoutId")
//                    mBinding = DataBindingUtil.setContentView(this, layoutId())
//                    (mBinding as ViewDataBinding).lifecycleOwner = this
//                }
//                ViewBinding::class.java.isAssignableFrom(cls) && cls != ViewBinding::class.java -> {
//                    cls.getDeclaredMethod("inflate", LayoutInflater::class.java).let {
//                        @Suppress("UNCHECKED_CAST")
//                        mBinding = it.invoke(null, layoutInflater) as DB
//                        setContentView(mBinding.root)
//                    }
//                }
//                else -> {
//                    if (layoutId() == 0) throw IllegalArgumentException("If you don't use ViewBinding, you need to override method layoutId")
//                    setContentView(layoutId())
//                }
//            }
            createViewModel(type.actualTypeArguments[0])
            //关联ViewModel
//            mBinding.setVariable(initVariableId(), viewModel)
        } else throw IllegalArgumentException("Generic error")
    }

    /**
     * 注册 UI 事件
     */
    private fun registerDefUIChange() {
        viewModel.defUI.showDialog.observe(this, {
            showLoading()
        })
        viewModel.defUI.dismissDialog.observe(this, {
            dismissLoading()
        })
        viewModel.defUI.toastEvent.observe(this, {
            FreeApi_ToastUtils.showFreeToast(it.message, this, it.isOk, 0)
        })
    }

    /**
     * 打开等待框
     */
    private fun showLoading() {
        (dialog ?: MaterialDialog(this)
            .cancelable(false)
            .cornerRadius(8f)
            .customView(R.layout.free_ui_glory_dialog_loading, noVerticalPadding = false)
            .lifecycleOwner(this)
            .maxWidth(R.dimen.dialog_width).also {
                dialog = it
            })
            .show()

    }

    /**
     * 关闭等待框
     */
    private fun dismissLoading() {
        dialog?.run { if (isShowing) dismiss() }
    }


    /**
     * 创建 ViewModel
     */
    @Suppress("UNCHECKED_CAST")
    fun createViewModel(type: Type) {
        val tClass = type as? Class<VM> ?: BaseViewModel::class.java
        viewModel = ViewModelProvider(viewModelStore, defaultViewModelProviderFactory)
            .get(tClass) as VM
    }

    override fun getDefaultViewModelProviderFactory(): ViewModelProvider.Factory {
        return MvvmConfig.getConfig().viewModelFactory()
            ?: super.getDefaultViewModelProviderFactory()
    }

    /**
     * 设置标题
     *
     * @param title
     */
    open fun setTitle(title: String?) {
        if (tvTitle != null) {
            tvTitle.text = title
        }
    }

    /**
     * 设置标题右侧文本按钮
     */
    open fun setRightListener(title: String, listener: View.OnClickListener?) {
        if (title.isNotEmpty()) {
            tvRight.visibility = View.VISIBLE
            tvRight.text = title
            tvRight.setOnClickListener(listener)
        } else {
            tvRight.visibility = View.GONE
        }
    }

    /**
     * 设置标题右侧图片按钮
     */
    open fun setRightListener(resID: Int, listener: View.OnClickListener?) {
        if (resID > 0) {
            ivRight.visibility = View.VISIBLE
            ivRight.setImageResource(resID)
            ivRight.setOnClickListener(listener)
        } else {
            ivRight.visibility = View.GONE
        }
    }

    /**
     * 跳转界面
     *
     * @param c 目标Activity
     */
    open fun startActivity(c: Class<*>?) {
        startActivity(Intent(this, c))
    }

    /**
     * 携带数据跳转界面
     *
     * @param c      目标Activity
     * @param bundle 携带数据
     */
    open fun startActivity(c: Class<*>?, bundle: Bundle?) {
        val intent = Intent(this, c)
        intent.putExtras(bundle!!)
        startActivity(intent)
    }

    override fun initViewTitle() {
        if (ivBack != null) {
            ivBack.setOnClickListener { finish() }
        }
    }

    override fun initParam() {
    }
}